/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.service.evaluation;

import cn.ac.nercis.pes.model.dto.common.Result;
import cn.ac.nercis.pes.model.dto.common.ResultCode;
import cn.ac.nercis.pes.model.dto.evaluation.prepare.PasswordServerDTO;
import cn.ac.nercis.pes.repository.dal.evaluation.PasswordServerRepository;
import cn.ac.nercis.pes.repository.mapper.evaluation.PasswordServerMapper;
import cn.ac.nercis.pes.repository.model.evaluation.PasswordServerDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 密码服务信息服务类
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
@Service
public class PasswordServerService {

    private final PasswordServerRepository passwordServerRepository;

    @Autowired
    public PasswordServerService(PasswordServerRepository passwordServerRepository) {
        this.passwordServerRepository = passwordServerRepository;
    }

    public List<PasswordServerDTO> findPasswordServer(String systemId){
        return this.passwordServerRepository.findAllBySystemId(systemId)
                .stream()
                .map(PasswordServerMapper.INSTANCE::toPwdServerDTO)
                .collect(Collectors.toList());
    }

    public Result<PasswordServerDTO> savePasswordServer(PasswordServerDTO passwordServer){
        if(StringUtils.isEmpty(passwordServer.getName())){
            passwordServer.setName("");
        }
        if(StringUtils.isEmpty(passwordServer.getVendor())){
            passwordServer.setVendor("");
        }
        try{
            if(StringUtils.isEmpty(passwordServer.getId())){
                return create(passwordServer);
            }else{
                return modify(passwordServer);
            }
        }catch (Exception e){
            log.error("保存测评工具信息出错：",e);
            return Result.failed();
        }
    }

    public Result<String> batchSavePasswordServer(List<PasswordServerDTO> data){
        Result<String> result = Result.success();
        for(PasswordServerDTO item : data){
            Result<PasswordServerDTO> itemResult = savePasswordServer(item);
            if(!itemResult.isSuccess()){
                result = Result.failed(ResultCode.FAIL);
                break;
            }
        }
        return result;
    }

    public Result<String> deletePasswordServer(String id){
        try{
            return this.passwordServerRepository.findById(id)
                    .map(passwordServerDO -> {
                        passwordServerRepository.delete(passwordServerDO);
                        return passwordServerDO;
                    })
                    .map(PasswordServerDO::getId)
                    .map(Result::success)
                    .orElse(Result.failed());
        }catch (Exception ex){
            log.error("删除密码服务信息出错：",ex);
            return Result.failed();
        }
    }

    public Result<String> batchDeletePasswordServer(Set<String> ids){
        Result<String> result = Result.success();
        for(String id : ids){
            Result<String> itemResult = deletePasswordServer(id);
            if(!itemResult.isSuccess()){
                result = Result.failed(ResultCode.FAIL);
                break;
            }
        }
        return result;
    }

    private Result<PasswordServerDTO> create(PasswordServerDTO passwordServer){
        return Optional.of(PasswordServerMapper.INSTANCE.toPwdServerDO(passwordServer))
                .map(e->{
                    e.setCreateTime(LocalDateTime.now());
                    return e;
                })
                .map(passwordServerRepository::save)
                .map(PasswordServerMapper.INSTANCE::toPwdServerDTO)
                .map(Result::success)
                .orElse(Result.failed());
    }

    private Result<PasswordServerDTO> modify(PasswordServerDTO passwordServer){
        PasswordServerDO source = this.passwordServerRepository.findById(passwordServer.getId()).orElse(null);
        if(Objects.isNull(source)){
            return Result.failed(ResultCode.NOT_FOUND);
        }
        return Optional.of(source)
                .map(s->{
                    s.setName(passwordServer.getName());
                    s.setVendor(passwordServer.getVendor());
                    s.setModifyTime(LocalDateTime.now());
                    return s;
                })
                .map(passwordServerRepository::save)
                .map(PasswordServerMapper.INSTANCE::toPwdServerDTO)
                .map(Result::success)
                .orElse(Result.failed(ResultCode.FAIL));
    }

}